package com.hongdee.crm.task.service.impl;

import com.hongdee.annotation.MethodComment;
import com.hongdee.crm.task.dao.IBcMaintainTypeTaskDao;
import com.hongdee.crm.task.dao.ITCrmCarMaintainTaskDao;
import com.hongdee.crm.task.dto.WorkOrderDTO;
import com.hongdee.crm.task.service.ITCrmCarWorkorderTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 名  称: TCrmCarWorkorderTaskServiceImpl
 * 类  型: class
 * 描  述: 计算工单信息
 * 路  径: com.hongdee.crm.task.service.impl
 * 作  者: wangshuai
 * 日  期: 2017/3/15
 */
@Service
public class TCrmCarWorkorderTaskServiceImpl implements ITCrmCarWorkorderTaskService {


    @Autowired
    private IBcMaintainTypeTaskDao maintainTypeTaskDao;
    @Autowired
    private ITCrmCarMaintainTaskDao carMaintainTaskDao;

    private Map<String, Object> typeMap = new HashMap<>();

    private final String DEFTYPE = "一般维修";
    private final int DEFLIMIT = 5000;

    /**
     * 1、根据类型参数设置 取出相应的公司信息
     * 2、遍历公司信息、取出公司对应的车辆品牌质保设置信息
     * 3、根据公司信息，取出公司所对应的维修项目与类型参数信息
     * 4、根据项目类型与参数信息，生成查询sql
     * 5、根据sql信息，查询相应工单信息
     * 6、根据工单对应的车辆品牌及质保信息，对比车辆品牌质保信息
     * 7、更新工单信息
     *
     * @throws Exception
     */
    @Override
    @MethodComment(name = "工单维修类型更新")
    public Integer bulidWorkorderPropertyQuartz() throws Exception {
        Integer nums = 0;
        List<Map<String, Object>> companyList = maintainTypeTaskDao.findCompanyList();
        if (companyList != null) {
            //遍历公司信息
            for (Map<String, Object> company : companyList) {
                String companyId = String.valueOf(company.get("company_id"));
                this.bulidWorkorderPropertyByCompanyQuqrtz(companyId);

            }
        }
        return nums;
    }

    /**
     * 根据公司更新工单维修类别
     *
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    @MethodComment(name = "根据公司ID更新工单维修类别")
    public Integer bulidWorkorderPropertyByCompanyQuqrtz(String companyId) throws Exception {
        setTypeOrder();
        Integer nums = 0;
        //获得公司下的品牌车辆所对应质保设置
        //根据公司取出维修项目信息
        List<Map<String, Object>> itemList = maintainTypeTaskDao.findMaintainTypeByComIdList(companyId);
        if (itemList != null) {
            int start = 0;
            while (true) {
                //生成查询sql
                String sql = this.toworkOrderSql(itemList, companyId, start, DEFLIMIT, WORDER_TYPE.wx.ordinal());
                System.out.println(sql);
                long start1 = System.currentTimeMillis();
                int num = carMaintainTaskDao.executeSQL(sql);
                if (num == 0) {
                    start = 0;
                    break;
                }
                nums += num;
                long end = System.currentTimeMillis();
                System.out.println("运行时间：" + (end - start1) + "毫秒");
//                    start++;
            }
        }
        return nums;
    }

    /**
     * 设置保养类型的排序号
     */
    private void setTypeOrder() {
        typeMap.put("首保", "1");
        typeMap.put("二保", "2");
        typeMap.put("定保", "3");
        typeMap.put("事故车", "4");
        typeMap.put("一般维修", "5");
    }

    /**
     * 生成查询sql
     *
     * @param itemList
     * @return
     */
    private String toworkOrderSql(List<Map<String, Object>> itemList, String companyId, int start, int limit, int type) {
        StringBuffer sql = new StringBuffer();
        sql.append("update t_crm_car_workorder worder,");
        sql.append("(");
        sql.append("select " +
                "t1.id,t1.company_id,t1.order_num,t1.balance_date,t1.type,t1.vin,t1.plate_num,t1.run_mile,t1.car_id,t1.amount,MIN(t1.mType) mType " +
                " from ( " +
                "SELECT * FROM( " +
                "SELECT t.id,t.company_id,t.order_num,t.balance_date,t.type,t2.vin,t.plate_num,t.run_mile,t.car_id, " +
                "CASE WHEN t.type = '索赔' THEN t.maintain_amount ELSE t.balance_amount END AS amount, " +
                "  CASE ");
        this.maintainType(itemList, sql);
        int order = Integer.valueOf(String.valueOf(typeMap.get(DEFTYPE)));
        sql.append(String.format("ELSE '%s%s' ", order, DEFTYPE));
        sql.append("END AS mType, t.create_time " +
                "FROM " +
                "(select * from t_crm_car_workorder where company_id='%s'");
        /**
         * 维修类别更新时 需要维修类别不等于空
         * 索赔类别更新时 不需要排除维修类别
         */
        if (type == WORDER_TYPE.wx.ordinal()) {
            sql.append(" AND wx_type IS NULL ");
        }

//                " and id='ff8081815ba4fe29015ba55cadd3052c' "+
        sql.append("ORDER BY balance_date ASC limit %d,%d ) t " +
                "left join " +
                "t_crm_car_workitem t2 " +
                "ON t.order_num = t2.order_code " +
                "AND t.company_id = t2.company_id " +
                ") worder  order by worder.mType ASC " +
                ")t1 group by t1.order_num" +
                " ");
        sql.append(") temp2 ");
        sql.append("set worder.wx_type=RIGHT(temp2.mType,CHAR_LENGTH(temp2.mType)-1),worder.type='维修' where worder.id=temp2.id");
        return String.format(sql.toString(), companyId, start, limit);
    }

    /**
     * 类别
     * 维修、索赔
     */
    private enum WORDER_TYPE {
        wx, sp
    }

    /**
     * 工单项目、维修类别
     */
    private enum MAINT_TYPE {
        ITEM_PROJ, ITEM_TYPE
    }


    private void maintainType(List<Map<String, Object>> itemList, StringBuffer sql) {
        for (Map<String, Object> item : itemList) {
            String pName = String.valueOf(item.get("maint_p_name"));
            String itemName = String.valueOf(item.get("maint_project_name"));
            String typeCode = String.valueOf(item.get("maint_ref"));
            //特殊处理
            if (pName.equals(DEFTYPE)) {
                continue;
            }
            String order = "";
            if (typeMap.get(pName) != null) {
                order = String.valueOf(typeMap.get(pName));
            }
//            int order = Integer.valueOf(String.valueOf(typeMap.get(pName)));
            if (typeCode.equals(String.valueOf(MAINT_TYPE.ITEM_PROJ.ordinal()))) {
                sql.append(String.format(" WHEN LOCATE('%s',t.maintain_type) THEN '%s%s' ", itemName, order, pName));
            } else {
                sql.append(String.format(" WHEN LOCATE('%s',t2.item_name) THEN '%s%s' ", itemName, order, pName));
            }
        }
    }


    //------------------------更新索赔类别--------------------------------------
    @Override
    @MethodComment(name = "更新工单索赔类别维修类别")
    public Integer bulidWorkorderPropertyBySpQuartz() throws Exception {
        Integer nums = 0;
        List<Map<String, Object>> companyList = maintainTypeTaskDao.findCompanyBySpList();
        if (companyList != null) {
            //遍历公司信息
            for (Map<String, Object> company : companyList) {
                String companyId = String.valueOf(company.get("company_id"));
                nums += this.bulidWorkorderPropertyBySpCompanyQuartz(companyId);
            }
        }
        return nums;
    }


    @Override
    @MethodComment(name = "根据公司ID更新工单索赔类维修类别")
    public Integer bulidWorkorderPropertyBySpCompanyQuartz(String companyId) throws Exception {
        Integer nums = 0;
        //获得公司下的品牌车辆所对应质保设置
        //根据公司取出维修项目信息
        List<Map<String, Object>> spItemList = maintainTypeTaskDao.findSpTypeByComIdList(companyId);
        nums += this.updWxType(spItemList, companyId, WORDER_TYPE.sp.ordinal());
        return nums;
    }

    private Integer updWxType(List<Map<String, Object>> itemList, String companyId, int type) throws Exception {
        Integer nums = 0;
        if (itemList != null) {
            int start = 0;
            int before = 0;
//            while (true) {
            //生成查询sql
            String sql = this.toworkSpOrderSql(itemList, companyId, start * DEFLIMIT, DEFLIMIT, type);
            System.out.println(sql);
            long start1 = System.currentTimeMillis();
            before = carMaintainTaskDao.executeSQL(sql);
//                if (before == 0) {
//                    start = 0;
//                    break;
//                }
            nums += before;
            long end = System.currentTimeMillis();
            System.out.println("运行时间：" + (end - start1) + "毫秒");
            start++;
//            }
        }
        return nums;
    }


    /**
     * 生成查询sql
     *
     * @param itemList
     * @return
     */
    private String toworkSpOrderSql(List<Map<String, Object>> itemList, String companyId, int start, int limit, int type) {
        StringBuffer sql = new StringBuffer();
        sql.append("update t_crm_car_workorder worder,");
        sql.append("(");
        sql.append("select " +
                "t1.id,t1.company_id,t1.order_num,t1.balance_date,t1.type,t1.vin,t1.plate_num,t1.run_mile,t1.car_id,t1.amount,MIN(t1.mType) mType " +
                " from ( " +
                "SELECT * FROM( " +
                "SELECT t.id,t.company_id,t.order_num,t.balance_date,t.type,t2.vin,t.plate_num,t.run_mile,t.car_id, " +
                "CASE WHEN t.type = '索赔' THEN t.maintain_amount ELSE t.balance_amount END AS amount, " +
                "  CASE ");
        this.maintainType(itemList, sql);
        sql.append(String.format("ELSE '%s%s' ", "", DEFTYPE));
        sql.append("END AS mType, t.create_time " +
                "FROM " +
                "(select * from t_crm_car_workorder where company_id='%s'  ");
        /**
         * 维修类别更新时 需要维修类别不等于空
         * 索赔类别更新时 不需要排除维修类别
         */
        if (type == WORDER_TYPE.wx.ordinal()) {
            sql.append(" AND wx_type IS NULL ");
        } else {
            sql.append(" and wx_type='一般维修' ");
        }

//                " and id='ff8081815ba4fe29015ba55cadd3052c' "+
        sql.append("ORDER BY wx_type ASC " +
//                "limit %d,%d " +
                ") t " +
                "left join " +
                "t_crm_car_workitem t2 " +
                "ON t.order_num = t2.order_code " +
                "AND t.company_id = t2.company_id " +
                ") worder  order by worder.mType ASC " +
                ")t1 group by t1.order_num" +
                " ");
        sql.append(") temp2 ");
        sql.append("set worder.wx_type=temp2.mType,worder.type='索赔' where worder.id=temp2.id and temp2.mType NOT IN ('一般维修')");
        return String.format(sql.toString(), companyId);//,start,limit);
    }

    /**
     * 产值计算
     *
     * @throws Exception
     */
    @Override
    @MethodComment(name = "工单产值计算")
    public Integer updWorkOrderAmountInfoQuartz() throws Exception {
        Integer sum = 0;
        //维修
        String wxSql = "update t_crm_car_workorder set real_amount = balance_amount  where type ='维修' ";
        sum += carMaintainTaskDao.executeSQL(wxSql);
        //索赔
        String spSQL = "update t_crm_car_workorder set real_amount = maintain_amount  where type ='索赔' ";
        sum += carMaintainTaskDao.executeSQL(spSQL);
        /**
         * 山东润捷单独处理-首保工单的产值取维修金额
         * **/
        String sqlBuf = "update  t_crm_car_workorder set real_amount = maintain_amount  where company_id ='ff8081815ccd7d16015cd2f181866d1e' and maintain_type = '0' ";
        sum += carMaintainTaskDao.executeSQL(sqlBuf);
        //sqlBuf = "update  t_crm_car_workorder set real_amount = maintain_amount  where company_id ='ff8081815ccd7d16015cd2f181866d1e' and maintain_type = 'M' ";
        //sum += carMaintainTaskDao.executeSQL(sqlBuf);

//        spSQL = "update t_crm_car_workorder set real_amount = maintain_amount  where wx_type in ('二保','首保')  and company_id in (select id  from t_bc_organ where o_car_brand='BUICK') ";
//        sum += carMaintainTaskDao.executeSQL(spSQL);
//
        //别克\雪弗兰 统一取维修金额
        spSQL = "update t_crm_car_workorder set real_amount = maintain_amount  where company_id in (select id  from t_bc_organ where o_car_brand in ('BUICK','CHEVROLET','')) ";
        sum += carMaintainTaskDao.executeSQL(spSQL);

        /******广汽菲克统一取结算金额******/
        spSQL = "update t_crm_Car_workorder o set real_amount = balance_amount where company_id in (select id from t_bc_organ where o_car_brand='GQFK')";
        sum += carMaintainTaskDao.executeSQL(spSQL);
        return sum;

    }

    //工单车辆ID

    /**
     * 更新工单车辆ID
     *
     * @throws Exception
     */
    @Override
    @MethodComment(name = "更新工单车辆ID")
    public Integer updWorkOrderCaridInfoQuartz() throws Exception {

        String sql = "update t_crm_car_workorder o " +
                "INNER JOIn t_crm_car c on o.plate_num= c.plate_num " +
                "and c.company_id= o.company_id " +
                "set o.car_id= c.id " +
                "where o.car_id is null ";
        return carMaintainTaskDao.executeSQL(sql);
    }
}
